package com.yumingjiang.weichatgtp;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        // 创建一个Semaphore，初始许可数量为3
        Semaphore semaphore = new Semaphore(3);

        // 创建10个线程模拟并发访问
        for (int i = 1; i <= 10; i++) {
            Thread thread = new Thread(new Task(semaphore, i));
            thread.start();
        }
    }

    static class Task implements Runnable {
        private Semaphore semaphore;
        private int taskId;

        public Task(Semaphore semaphore, int taskId) {
            this.semaphore = semaphore;
            this.taskId = taskId;
        }

        @Override
        public void run() {
            try {
                System.out.printf("Task %d 正在尝试获取许可...\n", taskId);
                semaphore.acquire(); // 获取许可，如果没有可用许可则阻塞等待
                System.out.printf("Task %d 获取了许可，开始执行任务...\n", taskId);
                Thread.sleep(2000); // 模拟任务执行时间
                System.out.printf("Task %d 释放了许可，任务执行完毕\n", taskId);
                semaphore.release(); // 释放许可
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}